package com.feijia.aijingjingus;

import android.animation.ObjectAnimator;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Html;
import android.text.Spannable;
import android.text.SpannableStringBuilder;
import android.text.style.AbsoluteSizeSpan;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TextView;

import com.bigkoo.pickerview.TimePickerView;
import com.bigkoo.pickerview.listener.CustomListener;
import com.timqi.sectorprogressview.ColorfulRingProgressView;

import org.json.JSONException;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import co.ceryle.radiorealbutton.RadioRealButton;
import co.ceryle.radiorealbutton.RadioRealButtonGroup;
import lecho.lib.hellocharts.gesture.ContainerScrollType;
import lecho.lib.hellocharts.gesture.ZoomType;
import lecho.lib.hellocharts.model.Axis;
import lecho.lib.hellocharts.model.AxisValue;
import lecho.lib.hellocharts.model.Line;
import lecho.lib.hellocharts.model.LineChartData;
import lecho.lib.hellocharts.model.PointValue;
import lecho.lib.hellocharts.model.ValueShape;
import lecho.lib.hellocharts.model.Viewport;
import lecho.lib.hellocharts.view.LineChartView;

import static com.feijia.aijingjingus.GlobalHelper.CalculateDaysBetweenDate;
import static com.feijia.aijingjingus.GlobalHelper.DaysBeforeOvulation;
import static com.feijia.aijingjingus.GlobalHelper.FirstDay;
import static com.feijia.aijingjingus.GlobalHelper.GUserNum;
import static com.feijia.aijingjingus.GlobalHelper.Menstruation;
import static com.feijia.aijingjingus.GlobalHelper.ONE_DAY_MS;
import static com.feijia.aijingjingus.GlobalHelper.OvulationLength;
import static com.feijia.aijingjingus.GlobalHelper.PeriodLength;

public class linearAnalysisActivity extends AppCompatActivity {

    private TabHost tabHost;
    private LineChartView week_HCG_lineChart,week_LH_lineChart,mouth_HCG_lineChart,mouth_LH_lineChart;
    private List<PointValue> mPointValues = new ArrayList<PointValue>(), LHPointValues = new ArrayList<PointValue>();
    private List<AxisValue> mAxisXValues = new ArrayList<AxisValue>(),mAxisTopXValues = new ArrayList<AxisValue>();
    private float maxValue=50;
    Line LHLine;
    Button btnYear,btnMonth;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
    Date SelectedDate;
    TimePickerView pvPickDay;
    ColorfulRingProgressView crpv;
    Handler handler =new Handler();
    Context context=this;
    int MonthSpan = 1;
    private TextView tvShowDate,tvShowDate2,tvDateDetail,tvPercent;

    final Runnable updateDateDetail = new Runnable() {
        @Override
        public void run() {
            try {
                Date date =  SelectedDate;
                tvShowDate2.setText(SimpleDateFormat.getDateInstance().format(date));
                Calendar cl = Calendar.getInstance();
                cl.setTime(date);
                cl.add(Calendar.DAY_OF_MONTH,-1);
                long nowDay = (cl.getTimeInMillis()/ ONE_DAY_MS)%Menstruation;
                date = format.parse(FirstDay);
                cl.setTime(date);
                long firstDay =(cl.getTimeInMillis()/ ONE_DAY_MS)%Menstruation;
                nowDay -=firstDay;
                if(nowDay<0)
                    nowDay+=Menstruation;
                cl.add(Calendar.DAY_OF_MONTH,PeriodLength);
                long firstDayAfterPeriod =(cl.getTimeInMillis()/ ONE_DAY_MS)%Menstruation-firstDay;
                long firstDayOfOvulation =DaysBeforeOvulation;
                long lastDayOfOvulation = firstDayOfOvulation+OvulationLength;
                long lastDay = firstDay+Menstruation-firstDay;
                firstDay=0;

                String str;
                int days;
                int PregnancyProbability=15;
                System.out.println("nowDay:"+nowDay+"  firstDayAfterPeriod:"+firstDayAfterPeriod+"  firstDayOfOvulation:"+firstDayOfOvulation+"  lastDayOfOvulation:"+lastDayOfOvulation+"  lastDay:"+lastDay+"  firstDay:"+firstDay);
                if(nowDay>=firstDay&&nowDay<firstDayAfterPeriod)
                {
                    days=(int)((nowDay-firstDay))+1;
                    PregnancyProbability=10;
                    str =String.format(getString(R.string.DayOfMenstrualPeriod_html),days);
                    //str = "This is the day <font color=\"#FF3366\">2</font> of the menstrual period.";
                }
                else if(nowDay>=firstDayAfterPeriod&&nowDay<firstDayOfOvulation)
                {
                    days=(int)((firstDayOfOvulation-nowDay));
                    if(days==1)
                        str =getString(R.string.DayBeforeOvulation_html);
                    else
                        str =String.format(getString(R.string.DaysBeforeOvulation_html),days);
                }
                else if (nowDay>=firstDayOfOvulation&&nowDay<lastDayOfOvulation)
                {
                    days=(int)((nowDay-firstDayOfOvulation))+1;
                    str =String.format(getString(R.string.DayOfOvulation_html),days);
                    PregnancyProbability=90-Math.abs(days-OvulationLength/2)*15;
                }
                else if (nowDay>=lastDayOfOvulation&&nowDay<lastDay)
                {
                    days=(int)((lastDay-nowDay));
                    str =String.format(getString(R.string.DaysBeforePeriod_html),days);
                }else
                {
                    days=(int)((firstDay-nowDay));
                    if(days==1)
                        str =getString(R.string.DayBeforePeriod_html);
                    else
                        str =String.format(getString(R.string.DaysBeforePeriod_html),days);
                }
                //str=""+days;
                tvDateDetail.setText(Html.fromHtml(str));
                ObjectAnimator crpvChange = ObjectAnimator.ofFloat(crpv,"Percent",crpv.getPercent(),PregnancyProbability).setDuration(500);
                crpvChange.start();
                //crpv.setPercent(PregnancyProbability);
                str=""+PregnancyProbability+"%\n"+getString(R.string.PregnancyProbability);
                SpannableStringBuilder style=new SpannableStringBuilder(str);
                AbsoluteSizeSpan span = new AbsoluteSizeSpan(24, true);
                style.setSpan(span,0,2, Spannable.SPAN_EXCLUSIVE_INCLUSIVE);

                tvPercent.setText(style);
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_linear_analysis);

        tvShowDate2 = (TextView)findViewById(R.id.tvShowDate2);
        tvDateDetail = (TextView)findViewById(R.id.tvDateDetail);
        tvPercent = (TextView)findViewById(R.id.tvPercent);
        crpv=(ColorfulRingProgressView)findViewById(R.id.crpv);
        final TextView tvDate = (TextView)findViewById(R.id.tvDate);

        final RadioRealButton rrbMonth = (RadioRealButton) findViewById(R.id.rrbMonth);
        final RadioRealButton rrbYear = (RadioRealButton) findViewById(R.id.rrbYear);
        RadioRealButtonGroup group = (RadioRealButtonGroup) findViewById(R.id.rrbGroup);
        group.setOnClickedButtonListener(new RadioRealButtonGroup.OnClickedButtonListener() {
            @Override
            public void onClickedButton(RadioRealButton button, int position) {
                if (button==rrbMonth)
                {
                    MonthSpan=1;
                }else
                {
                    MonthSpan=6;
                }
                Calendar cal = Calendar.getInstance();
                cal.setTime(SelectedDate);
                cal.add(Calendar.MONTH, -1*MonthSpan);
                Date start =cal.getTime();
                cal.add(Calendar.MONTH, 2*MonthSpan);
                Date end =cal.getTime();
                RefreshData(format.format(start),format.format(end));
            }
        });


        btnYear=(Button)findViewById(R.id.btnYear);
        btnMonth=(Button)findViewById(R.id.btnMonth);
        //Date dateStart = new Date(117,4,1);
        Date date = new Date();
        SelectedDate =date;
        final Calendar cal = Calendar.getInstance();
        cal.setTime(SelectedDate);
        cal.add(Calendar.MONTH, -1*MonthSpan);
        Date start =cal.getTime();
        cal.add(Calendar.MONTH, 2*MonthSpan);
        Date end =cal.getTime();
        cal.add(Calendar.MONTH, -1*MonthSpan);//复位
        week_HCG_lineChart=(LineChartView)findViewById(R.id.HCG_line_chart);
        mPointValues = getAxisPoints(mPointValues,start,end);
        //mAxisXValues = getAxisXLables(new String[]{"12-02","12-05","12-09","12-11","12-14","12-17","12-20","12-25","12-30","01-02","01-06","01-10","01-20","01-15"},mAxisXValues);
        mAxisXValues = MakeXAxisDayLabels(mAxisXValues,start,end);
        mAxisTopXValues = MakeXAxisMonthLabels(mAxisTopXValues,start,end);
        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）

        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
        line.setFilled(false);//是否填充曲线的面积
        line.setHasLabels(false);//曲线的数据坐标是否加上备注
//      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        line.setHasPoints(false);
        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示


        LHLine = new Line();
        LHLine.setColor(getResources().getColor(R.color.calendarview));
        LHLine.setShape(ValueShape.CIRCLE_SMALL);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
        LHLine.setCubic(false);//曲线是否平滑，即是曲线还是折线-
        LHLine.setFilled(false);//是否填充曲线的面积
        LHLine.setHasLabels(false);//曲线的数据坐标是否加上备注
        //      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
        LHLine.setHasPoints(true);
        LHLine.setHasLines(false);//是否用线显示。如果为false 则没有曲线只有点显示

        LHPointValues.add(DataToPointValue(start,"2017-8-4",10));
        LHPointValues.add(DataToPointValue(start,"2017-8-14",10));
        LHPointValues.add(DataToPointValue(start,"2017-8-24",10));
        LHLine.setValues(LHPointValues);
        initLineChart(week_HCG_lineChart,line,mAxisXValues,mAxisTopXValues);
        handler.post(updateDateDetail);
        tvDate.setText(format.format(date));
        tvDate.setClickable(true);
        tvDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                /*
                Calendar calendar = Calendar.getInstance();
                DatePickerDialog datePickerDialog = new DatePickerDialog(linearAnalysisActivity.this, new DatePickerDialog.OnDateSetListener() {

                    @Override
                    public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                        tvDate.setText(year + "-" + (monthOfYear+1) + "-" + dayOfMonth);
                        SelectedDate.setYear(year-1900);
                        SelectedDate.setMonth(monthOfYear);
                        SelectedDate.setDate(dayOfMonth);
                        System.out.println("Date:"+SelectedDate);
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(SelectedDate);
                        cal.add(Calendar.MONTH, -1);
                        Date start =cal.getTime();
                        cal.add(Calendar.MONTH, 2);
                        Date end =cal.getTime();
                        List<Line> lines = new ArrayList<Line>();
                        mPointValues = new ArrayList<PointValue>();
                        mPointValues = getAxisPoints(mPointValues,start,end);
                        Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）

                        line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
                        line.setCubic(true);//曲线是否平滑，即是曲线还是折线
                        line.setFilled(false);//是否填充曲线的面积
                        line.setHasLabels(false);//曲线的数据坐标是否加上备注
                //      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
                        line.setHasPoints(false);
                        line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
                        lines.add(line);
                        mAxisXValues = new ArrayList<AxisValue>();
                        mAxisTopXValues = new ArrayList<AxisValue>();
                        mAxisXValues = MakeXAxisDayLabels(mAxisXValues,start,end);
                        mAxisTopXValues = MakeXAxisMonthLabels(mAxisTopXValues,start,end);
                        ReloadLineChart(week_HCG_lineChart,lines,mAxisXValues,mAxisTopXValues);
                        //initLineChart(week_HCG_lineChart,line,mAxisXValues,mAxisTopXValues);
                    }

                }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.show();
                */
                Calendar selectedDate = cal;
                Calendar startDate = Calendar.getInstance();
                //startDate.set(2013,1,1);
                Calendar endDate = Calendar.getInstance();
                //endDate.set(2020,1,1);

                //正确设置方式 原因：注意事项有说明
                startDate.set(2013,0,1);
                endDate.set(2030,11,31);
                pvPickDay = new TimePickerView.Builder(context, new TimePickerView.OnTimeSelectListener() {
                    @Override
                    public void onTimeSelect(Date date,View v) {//选中事件回调
                        //pvPickDay.setText(sdf.format(date));
                        tvDate.setText((date.getYear()+1900) + "-" + (date.getMonth()+1) + "-" + date.getDate());
                        SelectedDate.setYear(date.getYear());
                        SelectedDate.setMonth(date.getMonth());
                        SelectedDate.setDate(date.getDate());
                        cal.set(date.getYear()+1900,date.getMonth(),date.getDate());
                        System.out.println("Date:"+SelectedDate);
                        Calendar cal = Calendar.getInstance();
                        cal.setTime(SelectedDate);
                        cal.add(Calendar.MONTH, -1*MonthSpan);
                        Date start =cal.getTime();
                        cal.add(Calendar.MONTH, 2*MonthSpan);
                        Date end =cal.getTime();
                        handler.post(updateDateDetail);
                        RefreshData(format.format(start),format.format(end));
                    }
                }).setLayoutRes(R.layout.pickerview_custom_day_options, new CustomListener() {
                    @Override
                    public void customLayout(View v) {
                        //自定义布局中的控件初始化及事件处理
                        final TextView tvSubmit = (TextView) v.findViewById(R.id.tv_finish);
                        ImageView ivCancel = (ImageView) v.findViewById(R.id.iv_cancel);
                        tvSubmit.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPickDay.returnData();
                                pvPickDay.dismiss();
                            }
                        });
                        ivCancel.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                pvPickDay.dismiss();
                            }
                        });

                    }
                })
                        .setLabel("","","","","","")
                        .setType(new boolean[]{true, true, true, false, false, false})// 默认全部显示
                        .isCyclic(true)//是否循环滚动
                        .setContentSize(24)
                        .setBgColor(0xEEEEEE)//滚轮背景颜色 Night mode
                        .setDate(selectedDate)// 如果不设置的话，默认是系统时间*/
                        .setRangDate(startDate,endDate)//起始终止年月日设定
                        .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                        .isDialog(true)//是否显示为对话框样式
                        .build();
                pvPickDay.show();
            }
        });
        System.out.println("start:"+start+"  end:"+end);
        RefreshData(format.format(start),format.format(end));

    }

    private void RefreshData(final String start, final String end)
    {
        new Thread(new Runnable() {
            @Override
            public void run() {
                JSONObject root= new JSONObject();
                try {
                    root.put("UserNo",Long.parseLong(GUserNum) /*Long.parseLong(GUserNum)*/);
                    root.put("DetectionDateStart", start);
                    root.put("DetectionDateEnd", end);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
                JSONObject out = GlobalHelper.PostData(root,"http://120.77.255.57/ting/getLHAVGs.php");
                System.out.println(out);
                try {
                    if (out.getInt("OperateResult")==1) {
                        String OperateMsg = out.getString("OperateMsg"); // 获取操作结果信息
                        System.out.printf(" OperateResult : %s \n OperateMsg : %s\n", out.getInt("OperateResult"), OperateMsg);
                        //JSONObject result = new JSONObject(out.getString("OperateMsg"));
                        LHPointValues.clear();
                        for (int i=0 ;i<out.getInt("ResultCount");i++){
                            JSONObject historyObject = new JSONObject(out.getString(""+i));
                            if(historyObject.getDouble("RawDetectionData")>200)
                            {
                                continue;
                            }
                            LHPointValues.add(DataToPointValue(format.parse(start),historyObject.getString("DetectionDate"),(float) historyObject.getDouble("RawDetectionData")));
                        }
                    } else {
                        System.out.println("predict error");
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                } catch (ParseException e) {
                    e.printStackTrace();
                }
                List<Line> lines = new ArrayList<Line>();
                mPointValues = new ArrayList<PointValue>();
                try {
                    mPointValues = getAxisPoints(mPointValues,format.parse(start),format.parse(end));

                Line line = new Line(mPointValues).setColor(Color.parseColor("#FFCD41"));  //折线的颜色（橙色）

                line.setShape(ValueShape.CIRCLE);//折线图上每个数据点的形状  这里是圆形 （有三种 ：ValueShape.SQUARE  ValueShape.CIRCLE  ValueShape.DIAMOND）
                line.setCubic(true);//曲线是否平滑，即是曲线还是折线
                line.setFilled(false);//是否填充曲线的面积
                line.setHasLabels(false);//曲线的数据坐标是否加上备注
                //      line.setHasLabelsOnlyForSelected(true);//点击数据坐标提示数据（设置了这个line.setHasLabels(true);就无效）
                line.setHasPoints(false);
                line.setHasLines(true);//是否用线显示。如果为false 则没有曲线只有点显示
                lines.add(line);
                mAxisXValues = new ArrayList<AxisValue>();
                mAxisTopXValues = new ArrayList<AxisValue>();
                mAxisXValues = MakeXAxisDayLabels(mAxisXValues,format.parse(start),format.parse(end));
                mAxisTopXValues = MakeXAxisMonthLabels(mAxisTopXValues,format.parse(start),format.parse(end));
                ReloadLineChart(week_HCG_lineChart,lines,mAxisXValues,mAxisTopXValues);
                } catch (ParseException e) {
                    e.printStackTrace();
                }
            }

        }).start();
    }

    /**
     * 设置X 轴的显示
     */
    private List<AxisValue> getAxisXLables(String[] date,List<AxisValue> mAxisXValues){
        for (int i = 0; i < date.length; i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(date[i]));
        }
        return mAxisXValues;
    }
    private List<PointValue> getAxisPoints(List<PointValue> mPointValues,Date dateStart,Date dateEnd) {
        float step=0.2f;
        Date date=new Date();
        try {
            date = format.parse(FirstDay);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        float firstDay =CalculateDaysBetweenDate(dateStart,date);
        float length=CalculateDaysBetweenDate(dateStart,dateEnd);
        for (float i = 0; i < length; i+=step) {
            mPointValues.add(new PointValue(i, (float) fLH(i-firstDay)));
        }
        return mPointValues;
    }

    private List<AxisValue> MakeXAxisDayLabels(List<AxisValue> mAxisXValues, Date dateStart, Date dateEnd) {
        int length = CalculateDaysBetweenDate(dateStart,dateEnd);
        Date dateTemp = dateStart;
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateTemp);
        for (int i = 0; i < length; i++) {
            mAxisXValues.add(new AxisValue(i).setLabel(""+dateTemp.getDate()));

            cal.add(Calendar.DATE, 1);
            dateTemp =cal.getTime();
        }
        return mAxisXValues;
    }
    private List<AxisValue> MakeXAxisMonthLabels(List<AxisValue> mAxisXValues, Date dateStart, Date dateEnd) {
        int length = CalculateDaysBetweenDate(dateStart,dateEnd);
        Date dateTemp = dateStart;
        Calendar cal = Calendar.getInstance();
        cal.setTime(dateTemp);
        for (int i = 0; i < length; i++) {
            if(dateTemp.getDate()==1) {
                mAxisXValues.add(new AxisValue(i).setLabel("" + (dateTemp.getMonth()+1)));
                cal.add(Calendar.DATE, 25);
                i+=25;
            }
            cal.add(Calendar.DATE, 1);
            dateTemp =cal.getTime();
        }
        return mAxisXValues;
    }

    private void initLineChart(LineChartView lineChart,Line line, List<AxisValue> mAxisXValues,List<AxisValue> mAxisTopXValues){
        List<Line> lines = new ArrayList<Line>();
        lines.add(line);
        ArrayList<PointValue> tempV =new ArrayList<PointValue>();
        tempV.add(new PointValue(0,maxValue));
        tempV.add(new PointValue(0,0));
        Line noneline = new Line(tempV).setColor(Color.parseColor("#00FFCD41"));
        lines.add(noneline);
        lines.add(LHLine);
        LineChartData data = new LineChartData();
        data.setLines(lines);

        //坐标轴
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.WHITE);  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(10); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        Axis axisTopX = new Axis(); //X轴
        axisTopX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisTopX.setTextColor(Color.WHITE);  //设置字体颜色
        //axisTopX.setName("date");  //表格名称
        axisTopX.setTextSize(16);//设置字体大小
        axisTopX.setMaxLabelChars(10); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=maxisTopXValues.length
        axisTopX.setValues(mAxisTopXValues);  //填充X轴的坐标名称
        //data.setAxisXBottom(axisTopX); //x 轴在底部
        data.setAxisXTop(axisTopX);  //x 轴在顶部
        axisTopX.setHasLines(true); //x 轴分割线

        // Y轴是根据数据的大小自动设置Y轴上限(在下面我会给出固定Y轴数据个数的解决方案)
        Axis axisY = new Axis().setHasLines(true);
        axisY.setMaxLabelChars(5);//max label length, for example 60
        axisY.setTextColor(Color.WHITE);
        List<AxisValue> values = new ArrayList<>();
        for(int i = 0; i < 100; i+=10){
            AxisValue value = new AxisValue(i);
            values.add(value);
        }
        axisY.setValues(values);
        axisX.setHasLines(true);
        data.setAxisYLeft(axisY);
        //data.setAxisYRight(axisY);  //y轴设置在右边


        //设置行为属性，支持缩放、滑动以及平移
        lineChart.setInteractive(true);
        lineChart.setZoomType(ZoomType.HORIZONTAL);
        lineChart.setMaxZoom((float) 2);//最大方法比例
        lineChart.setContainerScrollEnabled(true, ContainerScrollType.HORIZONTAL);
        lineChart.setLineChartData(data);
        lineChart.setVisibility(View.VISIBLE);
        /**注：下面的7，10只是代表一个数字去类比而已
         * 当时是为了解决X轴固定数据个数。见（http://forum.xda-developers.com/tools/programming/library-hellocharts-charting-library-t2904456/page2）;
         */
        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.left = 13;
        v.right= 20;
        v.bottom=0;
        v.top=100;
        lineChart.setCurrentViewport(v);
    }
    private void  ReloadLineChart(LineChartView lineChart,List<Line> lines, List<AxisValue> mAxisXValues,List<AxisValue> mAxisTopXValues)
    {
        ArrayList<PointValue> tempV =new ArrayList<PointValue>();
        tempV.add(new PointValue(0,maxValue));
        tempV.add(new PointValue(0,0));
        Line noneline = new Line(tempV).setColor(Color.parseColor("#00FFCD41"));
        lines.add(noneline);
        LineChartData data = new LineChartData();
        data.setLines(lines);
        LHLine.setValues(LHPointValues);
        lines.add(LHLine);
        Axis axisX = new Axis(); //X轴
        axisX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisX.setTextColor(Color.WHITE);  //设置字体颜色
        //axisX.setName("date");  //表格名称
        axisX.setTextSize(10);//设置字体大小
        axisX.setMaxLabelChars(10); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=mAxisXValues.length
        axisX.setValues(mAxisXValues);  //填充X轴的坐标名称
        data.setAxisXBottom(axisX); //x 轴在底部
        //data.setAxisXTop(axisX);  //x 轴在顶部
        axisX.setHasLines(true); //x 轴分割线

        Axis axisTopX = new Axis(); //X轴
        axisTopX.setHasTiltedLabels(false);  //X坐标轴字体是斜的显示还是直的，true是斜的显示
        axisTopX.setTextColor(Color.WHITE);  //设置字体颜色
        //axisTopX.setName("date");  //表格名称
        axisTopX.setTextSize(16);//设置字体大小
        axisTopX.setMaxLabelChars(10); //最多几个X轴坐标，意思就是你的缩放让X轴上数据的个数7<=x<=maxisTopXValues.length
        axisTopX.setValues(mAxisTopXValues);  //填充X轴的坐标名称
        //data.setAxisXBottom(axisTopX); //x 轴在底部
        data.setAxisXTop(axisTopX);  //x 轴在顶部
        axisTopX.setHasLines(true); //x 轴分割线

        lineChart.setLineChartData(data);
        Viewport v = new Viewport(lineChart.getMaximumViewport());
        v.left = 15;
        v.right= 22;
        v.bottom=0;
        v.top=100;
        lineChart.setCurrentViewport(v);
    }
    public void onClickDetection(View view)
    {
        finish();
        Intent intent =new Intent("controlCenterActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
    public void onClickUser(View view)
    {
        finish();
        Intent intent =new Intent("ImprovePersonalInformationActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
    public void onClickBack(View view)
    {
        finish();
    }
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            Intent intent =new Intent("controlCenterActivity");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
            startActivity(intent);
        }
        return false;
    }
    public void onClickDetectionHistory(View view)
    {
        finish();
        Intent intent =new Intent("detectionHistoryActivity");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_CLEAR_TASK);
        startActivity(intent);
    }
    public void onClickYear(View view)
    {
        MonthSpan=1;
        System.out.println("MonthSpan:"+MonthSpan);
    }
    public void onClickMonth(View view)
    {
        MonthSpan=6;
        System.out.println("MonthSpan:"+MonthSpan);
    }

    public PointValue DataToPointValue(Date StartDate,String Date,float Data)
    {
        PointValue rn = new PointValue();
        Date date;
        try {
            date = format.parse(Date);
        } catch (ParseException e) {
            date = new Date();
            e.printStackTrace();
        }
        rn.set(CalculateDaysBetweenDate(StartDate,date),Data);
        return rn;
    }

    public double fLH(double x)
    {
        x+=2;
        x=x%Menstruation;
        BigDecimal bd = new BigDecimal(x);
        x = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
        x=Math.abs(x) -15;
        double y;
        double a1 =       36.74f;
        double b1 =     0.04382f;
        double c1 =      0.7957f;
        double a2 =       6.026f;
        double b2 =     -0.9494f;
        double c2 =       15.97f;
        double y0 = a1*Math.exp(Math.pow(((x-b1)/c1),2)*-1);
        double y1 = a2*Math.exp(Math.pow(((x-b2)/c2),2)*-1);
        y=y0+y1;
        return y;
    }
}
